import { defineStore } from "pinia";
import { getUserInfo } from "@/utils/auth";
import {
  myVisitorAPI,
  myCustomerAPI,
  myCustomerTagsAPI,
  teamCustomerListAPI,
  teamVisitListAPI,
  getMydprtAPI,
  memberBoardAPI,
  teamBoardAPI,
  getTeamBoardOverviewAPI,
  teamReportListAPI,
  teamReportCustomerListAPI,
  teamReportDetailConferenceAPI,
  teamBoardUsersAPI,
  teamBoardSubteamAPI,
  getTeamReportLatest2API,
  getAssessmentSettingsAPI,
  getPassScore,
  getCommunicationFlowsAPI,
  getCommunicationStagesAPI
} from "@/services/myXmate";
import { searchInnerAttendPagerAPI } from "@/services/orderVisit";


import dayjs from "dayjs";
import { getDateRange } from "@/utils/timeTool";

const defaultDateRange = getDateRange("quarter");

export const useMyXmateStore = defineStore("myXmate", {
  state: () => ({
    myVisitList: [],
    systemTags: [],
    noMoreData: false,
    myCustomerList: [],
    // 客户沟通环节
    customerCommunicationStages: [],
    teamCustomerList: [],
    teamVisitorList: [],
    memberBoardList: [], // 成员数据
    teamBoardList: [], // 团队数据
    teamOverview: {}, // 团队看板总览
    teamReportOverview: {}, // 团队报告总览 （和团队看板一个接口，只是部门和纬度不同）
    teamOverviewMemberList: {},
    teamVisitorNoMoreData: false,
    selfDprt: undefined,
    filterParams: {
      myVisit: {},
      myCustomer: {},
      teamVisit: {},
      teamCustomer: {}
    },
    teamReportList: [],
    teamReportCustomerList: [],
    orgId: getUserInfo().orgId,
    userId: getUserInfo().id,
    // 团队看板公共参数
    noticeBoardPublicParam: {
      startDate: defaultDateRange.startDate,
      endDate: defaultDateRange.endDate,
      reportType: "quarterly",
      currentDept: null,
      alreadySetDefaultDept: false,
      candidateList: [],
      taskStandardScore: null,
      abilityStandardScore: null,
    },
    assessmentSettings: null,
    // 所有沟通环节 （客户、商机）
    communicationFlows: []
  }),

  /*
  查询自己信息,
  缓存自己信息
  将自己信息添加到participantList中
*/
  actions: {
    async getVisitorListAction(parameter) {
      const { pageNumber, pageSize } = parameter;

      const data = await myVisitorAPI(parameter);
      const list = data.datas || [];
      this.noMoreData = list.length < pageSize;
      if (pageNumber > 1) {
        this.myVisitList = this.myVisitList.concat(list);
      } else {
        this.myVisitList = list;
      }
    },

    async getCommunicationFlowsAction() {
      const data = await getCommunicationFlowsAPI();
      this.communicationFlows = data.datas || [];
    },

    async getMyCustomerAction(parameter) {
      const { pageNumber } = parameter;
      const data = await myCustomerAPI(parameter);
      const list = data.datas || [];
      if (pageNumber > 1) {
        this.myCustomerList = this.myCustomerList.concat(list);
      } else {
        this.myCustomerList = list;
      }
      console.log("getMyCustomerAction list: ", list);
      return list;
    },

    async getCustomerCommunicationStages() {
      const data = await getCommunicationStagesAPI({ type: 0 });
      this.customerCommunicationStages = data.datas;
    },

    async getTeamCustomerListAction(parameter) {
      const data = await teamCustomerListAPI(parameter);
      this.teamCustomerList = data.datas || [];
    },

    async getTeamVisitListAction(parameter) {
      const { pageNumber, pageSize } = parameter;
      const data = await teamVisitListAPI(parameter);
      let list = data.datas || [];
      if (list.length < pageSize) {
        this.teamVisitorNoMoreData = true;
      }
      if (pageNumber > 1) {
        this.teamVisitorList.push(...(list || []));
      } else {
        this.teamVisitorNoMoreData = false;
        this.teamVisitorList = list;
      }
      
    },

    async getMydprtAction( ) {
      // 先使用缓存做一次赋值
      console.log("debug -- getMydprtAction");
      if (!this.alreadySetDefaultDept) {
        this.noticeBoardPublicParam.currentDept = this.getDefaultDept;
      }
      const data = await getMydprtAPI();
      this.selfDprt = data;
      if (!this.alreadySetDefaultDept) {
        this.noticeBoardPublicParam.currentDept = this.getDefaultDept;
        await this.generatedCandidateList();
      }
      this.updatePassScore();
      this.alreadySetDefaultDept = true;
      return data;
    },

    // 生成待选人员接口
    async generatedCandidateList(deptIds) {
      const parameter = {
        deptIds,
        includeChildren: true,
        queryManagedDepartment: true,
        pageNumber: 1,
        pageSize: 10
      };
      const data = await searchInnerAttendPagerAPI(parameter);
      console.log("generatedCandidateList: ", data);
      this.noticeBoardPublicParam.candidateList = data.datas;
      return data;
    },

    async getMemberBoardAction(teamId, periodType, parameter) {
      const data = await memberBoardAPI(teamId, periodType, parameter);
      this.memberBoardList = data.datas || [];
    },

    async getTeamBoardAction(teamId, periodType, parameter) {
      const data = await teamBoardAPI(teamId, periodType, parameter);
      this.teamBoardList = data.datas || [];
    },

    async getTeamBoardOverviewAction(teamId, periodType) {
      const data = await getTeamBoardOverviewAPI(teamId, periodType);
      this.teamOverview = data;
    },

    async getTeamReportOverviewAction(teamId, periodType) {
      const data = await getTeamBoardOverviewAPI(teamId, periodType);
      this.teamReportOverview = data;
    },

    async getTeamBoardUserAction(teamId, parameter = {}) {
      const data = await teamBoardUsersAPI(teamId, parameter);
      this.teamOverviewMemberList = data.datas || [];
    },

    async getTeamBoardSubteamAction(teamId, parameter = {}) {
      const data = await teamBoardSubteamAPI(teamId, parameter);
      this.teamOverviewTeamList = data.datas || [];
    },

    async getTeamReportListAction(parameter = {}) {
      parameter.orgId = this.orgId;
      parameter.userId = this.userId;
      const data = await teamReportListAPI(parameter);
      console.log("getTeamReportListAction data: ", data);
      this.teamReportList = data.datas || [];
    },
    async getTeamReportCustomerListAction(parameter) {
      parameter.orgId = this.orgId;
      parameter.userId = this.userId;
      const data = await teamReportCustomerListAPI(parameter);
      console.log("getTeamReportListAction data: ", data);
      this.teamReportCustomerList = data.datas || [];
    },

    async getTeamReportDetailAction(parameter) {
      parameter.orgId = this.orgId;
      parameter.userId = this.userId;
      console.log("teamReportDetailConferenceAPI: ", parameter);
      const data = await teamReportDetailConferenceAPI(parameter);
      console.log("getTeamReportDetailAction data: ", data);
      return data.datas;
    },

    // getTeamReportLatest2API
    async getTeamReportLatest2Action(teamId, periodType, reportTime) {
      const data = await getTeamReportLatest2API(
        teamId,
        periodType,
        reportTime
      );
      this.teamReportLatest2 = data.datas || [];
      return data.datas;
    },

    async getAssessmentSettingsAction() {
      const data = await getAssessmentSettingsAPI();
      this.assessmentSettings = data;
    },

    async updatePassScore() {
      const data = await getPassScore(this.orgId);
      console.log("getPassScore: ", data);
      const { abilityScore4Pass, taskRate4Pass } = data;
      if (!taskRate4Pass || !taskRate4Pass) {
        console.error("达标值获取异常");
      }
      this.noticeBoardPublicParam.taskStandardScore = taskRate4Pass || 80;
      this.noticeBoardPublicParam.abilityStandardScore = abilityScore4Pass || 80;
    }
  },

  getters: {
    getDefaultDept() {
      if (!this.selfDprt) return  null;
      const { children } = this.selfDprt;
      if (!children || children.length === 0) {
        return this.selfDprt;
      }
      return  children[0];
    },
    isLastLevelDepartment() {
      if (!this.noticeBoardPublicParam?.currentDept) {
        return false;
      }
      return this.noticeBoardPublicParam?.currentDept.children.length <= 0;
    }
  },

  persist: {
    enabled: true,
    key: "myXmate",
    storage: sessionStorage,
    pick: ["systemTags", "selfDprt", "communicationFlows"]
  }
});
